local FOR_BUILD=9464  --GetBuildInfo()
WarbabyTradeLinkData = {}

SLASH_WARBABY_TRADE_LINK1 = "/tradelink";
SLASH_WARBABY_TRADE_LINK2 = "/tl";
SlashCmdList["WARBABY_TRADE_LINK"] = function (cmd)
	local color = "|cff7F7Fff";
	if(cmd=="CLEAR") then
		WarbabyTradeLinkData = {};
		DEFAULT_CHAT_FRAME:AddMessage(color.."Warbaby'sTradeLink數據已經清空，請重新收集。|r");
		return;
	end
	DEFAULT_CHAT_FRAME:AddMessage(color.."專業技能鏈接大全 作者 : Warbaby @ 聖光之願 <冰封十字軍>");
	DEFAULT_CHAT_FRAME:AddMessage(color.."  * 如果沒有某種技能, 請讓朋友發一次鏈接|r");
	DEFAULT_CHAT_FRAME:AddMessage(color.."  * 如果遊戲更新導致鏈接失效, 請運行'/tl CLEAR'清除過期數據|r");
	local curr = tonumber(cmd) or 450;
	local k,v,i,all;
	all = "";
	for k,v in pairs(WarbabyTradeLinkData) do
		local s = format("%0"..v.len.."d", 0);
		all = all..(" |c"..v.color.."|Htrade:"..v.id..":"..curr..":450:"..v.uid..":"..string.gsub(s,"0","/").."|h["..v.name.."]|h|r");
	end
	DEFAULT_CHAT_FRAME:AddMessage(all);
end


function WBTradeLink_GetTradeLink(self, message)
	if message then
		--ChatFrame2:AddMessage(string.gsub(message, "|", "$"));
		--if(string.find(message, "%|Htrade:")) then ChatFrame1:AddMessage(string.gsub(message, "|", "$")); end
		--if(string.find(message, "%|Htrade:")) then ChatFrame1:AddMessage("-------------"); end
		while(true) do
			local start, finish, color, trade, id, uid, list, name = string.find(message, "%|c(%x+)%|H(trade):(%d-):%d-:%d-:(%x-):([^|:]+)%|h%[([^%]]-)%]%|h%|r");
			if(not start) then
				start, finish, trade, color, id, uid, list, name = string.find(message, "{CLINK:(trade):(%x+):(%d-):%d-:%d-:(%x-):([^|:]+):([^}]-)}");
			end
			if(start) then
				--ChatFrame1:AddMessage(color..", "..trade..", "..id..", "..uid..", "..strlen(list)..", "..name);
				WarbabyTradeLinkData[name] = {
					["id"] = id,
					["uid"] = uid,
					["len"] = strlen(list),
					["name"] = name,
					["color"] = color,
				}
				message = string.sub(message, finish);
			else
				break;
			end
		end
	end
end

local i;
for i=1, 7 do
	if(getglobal("ChatFrame"..i)) then
		hooksecurefunc(getglobal("ChatFrame"..i), "AddMessage", WBTradeLink_GetTradeLink)
	end
end



local function SetOrHookScript(frame, scriptName, func)
	if( frame:GetScript(scriptName) ) then
		frame:HookScript(scriptName, func);
	else
		frame:SetScript(scriptName, func);
	end
end


TradeSkillFrame_LoadUI()

for i=1,20 do
	local btn = getglobal("TradeSkillSkill"..i);
	if btn then
		SetOrHookScript(btn, "OnEnter", function (self)
			local id = self:GetID();
			local skillName, skillType, numAvailable, isExpanded, altVerb = GetTradeSkillInfo(id);
			if(skillType=="header") then
				GameTooltip:Hide();
				CursorUpdate(self);
			else
				GameTooltip:SetOwner(self, "ANCHOR_RIGHT");
				GameTooltip:SetTradeSkillItem(id);
				--GameTooltip:Hide();
				CursorUpdate(self);

				local numReagents = GetTradeSkillNumReagents(id);
				if(numReagents > 0) then
					GameTooltip:AddLine("-----------------------");
					local i;
					for i=1, numReagents, 1 do
						local reagentName, reagentTexture, reagentCount, playerReagentCount = GetTradeSkillReagentInfo(id, i);
						if(reagentName) then
							GameTooltip:AddLine(reagentName.."("..playerReagentCount.."/"..reagentCount..")");
						end
					end
					GameTooltip:Show();
				end
			end;

		end)

		SetOrHookScript(btn, "OnLeave", function (self)
			GameTooltip:Hide();
		end)

		btn:RegisterForClicks("LeftButtonUp","RightButtonUp");

		SetOrHookScript(btn, "OnClick", function (self, button)
			if ( IsModifiedClick() and button=="RightButton") then
				local link = GetTradeSkillRecipeLink(self:GetID())
				if link then
					local _, _, id = string.find(link, "%|c%x+%|Henchant:(%d-)%|h%[[^%]]-%]%|h%|r");
					id = "http://db.duowan.com/spell-"..id..".html";
					ChatFrameEditBox:Show();
					ChatFrameEditBox:SetText(id);
					ChatFrameEditBox:HighlightText(0, -1);
				end
			end
		end)
	end
end

local function GetMaskChar(b) --0-25(A-Z) 26-51(a-z) (52-61)0-9 62(+) 63(/)
	return strchar( b<26 and b+65 or b<52 and b-26+97 or b<62 and b-52+48 or b==62 and 43 or 47)
end

local function GetMaskByte(b)
	return b==43 and 62 or b==47 and 63 or b<=57 and b-48+52 or b<=90 and b-65 or b<=122 and b-97+26
end

TradeSkillLinkButton:RegisterForClicks("LeftButtonUp","RightButtonUp");
SetOrHookScript(TradeSkillLinkButton, "OnClick", function(self, button)
	if(button=="RightButton") then
		local link=GetTradeSkillListLink();
		if link then
			local start, finish, color, trade, id, uid, list, name = string.find(link, "%|c(%x+)%|H(trade):(%d-):%d-:%d-:(%x-):([^|:]+)%|h%[([^%]]-)%]%|h%|r");
			local l2 = ""
			local i
			for i=1, #list do
				local b = GetMaskByte(strbyte(list, i));
				if i==1 then
					b = bit.bxor(b, 31)
				else
					b = bit.bxor(b, 63)
				end
				l2 = l2..GetMaskChar(b);
			end
			link = "|c"..color.."|Htrade:"..id..":".."0"..":450:"..uid..":"..l2.."|h["..name.."]|h|r";

			if(ChatFrameEditBox:IsVisible()) then ChatFrameEditBox:Hide() end;
			DEFAULT_CHAT_FRAME:AddMessage("所有你缺少的"..name.."配方是："..link);
			DEFAULT_CHAT_FRAME:AddMessage("SHIFT+右鍵點擊技能標題可以得到資料庫網址");
		end
	end
end)


--[[
SetOrHookScript(TradeSkillLinkButton, "OnShow", function(self)
	ChatFrame1:AddMessage(111);
	local link=GetTradeSkillListLink();
	if link then
		ChatFrame1:AddMessage(link);
		WBTradeLink_GetTradeLink(nil, link);
	end
end)
]]

hooksecurefunc("TradeSkillFrame_Update", function(self)
	local link=GetTradeSkillListLink();
	if link then
		WBTradeLink_GetTradeLink(nil, link);
	end
end);
